package com.sinoeyes.controller.system;

import com.sinoeyes.auth.core.util.SecurityUtils;
import com.sinoeyes.common.constant.UserConstants;
import com.sinoeyes.common.core.controller.BaseController;
import com.sinoeyes.common.core.page.RestPageResult;
import com.sinoeyes.common.result.RCode;
import com.sinoeyes.common.result.Result;
import com.sinoeyes.framework.aspectj.lang.annotation.Log;
import com.sinoeyes.framework.aspectj.lang.enums.BusinessType;
import com.sinoeyes.system.filter.SysUserFilter;
import com.sinoeyes.system.service.ISysPostService;
import com.sinoeyes.system.service.ISysRoleService;
import com.sinoeyes.system.service.ISysUserService;
import com.sinoeyes.system.vo.SysUserVo;
import com.sinoeyes.vo.system.UserProfileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户信息
 *
 */
@RestController
@RequestMapping("/system/user")
@Api(value = "用户信息 API", tags = {"用户信息"})
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    @ApiOperation("获取用户列表")
    public Result<RestPageResult<SysUserVo>> list(SysUserFilter userFilter)
    {
        RestPageResult<SysUserVo> pageResult = userService.selectUserList(userFilter);
        return Result.success(pageResult);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = "/{userId}")
    @ApiOperation("根据用户编号获取详细信息")
    public Result<UserProfileVo> getInfo(@PathVariable Long userId)
    {
        UserProfileVo userProfileVo = new UserProfileVo();
        userProfileVo.setUserVo(userService.selectUserById(userId));
        userProfileVo.setPostIds(postService.selectPostListByUserId(userId));
        userProfileVo.setRoleIds(roleService.selectRoleListByUserId(userId));
        return Result.success(userProfileVo);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增用户")
    public Result<Integer> add(@RequestBody SysUserVo user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return Result.failure(RCode.PARAM_VALID_ERROR.getCode(),"新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return Result.failure(RCode.PARAM_VALID_ERROR.getCode(),"新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return Result.failure(RCode.PARAM_VALID_ERROR.getCode(),"新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return Result.success(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改用户")
    public Result<Integer> edit(@RequestBody SysUserVo user)
    {
        userService.checkUserAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return Result.failure(RCode.PARAM_VALID_ERROR.getCode(),"修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return Result.failure(RCode.PARAM_VALID_ERROR.getCode(),"修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return Result.success(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userId}")
    @ApiOperation("删除用户")
    public Result<Integer> remove(@PathVariable Long userId)
    {
        userService.checkUserAllowed(new SysUserVo(userId));
        return Result.success(userService.deleteUserById(userId));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    @ApiOperation("重置密码")
    public Result<Integer> resetPwd(@RequestBody SysUserVo user)
    {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return Result.success(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @ApiOperation("状态修改")
    public Result<Integer> changeStatus(@RequestBody SysUserVo user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return Result.success(userService.updateUserStatus(user));
    }
}